namespace OneWorks.Utils.FluentData
{
    using System;

    internal class QueryScalarHandler<TEntity> : IQueryTypeHandler<TEntity>
    {
        private readonly DbCommandData _data;
        private Type _fieldType;

        public bool IterateDataReader { get { return true; } }

        public QueryScalarHandler(DbCommandData data)
        {
            this._data = data;
        }

        public object HandleType(Action<TEntity, IDataReader> customMapperReader, Action<TEntity, dynamic> customMapperDynamic)
        {
            var value = this._data.Reader.GetValue(0);
            if (this._fieldType == null)
                this._fieldType = this._data.Reader.GetFieldType(0);

            if (value == null)
                value = default(TEntity);
            else if (this._fieldType != typeof(TEntity))
                value = (Convert.ChangeType(value, typeof(TEntity)));
            return (TEntity)value;
        }
    }
}